package com.tbabs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tbabs.common.R;
import com.tbabs.dto.DishDto;
import com.tbabs.entity.Category;
import com.tbabs.entity.Dish;
import com.tbabs.entity.DishFlavor;
import com.tbabs.service.CategoryService;
import com.tbabs.service.DishFlavorService;
import com.tbabs.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);

        // 清除redis缓存
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("新增菜品成功！");
    }

    @GetMapping("/page")
    public R<Page<DishDto>> getDishByPage(int page, int pageSize, @RequestParam(required = false) String name){
        Page<Dish> dishInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name)
                .orderByDesc(Dish::getUpdateTime);

        dishService.page(dishInfo, queryWrapper);

        // 对象拷贝，除了records属性都拷贝
        BeanUtils.copyProperties(dishInfo, dishDtoPage, "records");

        List<Dish> records = dishInfo.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getDishInfo(@PathVariable Long id){
        DishDto dishDto = dishService.getInfoByIDWithFlavor(id);

        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateDish(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);

        // 清除redis缓存
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("修改菜品成功！");
    }

    @DeleteMapping
    public R<String> deleteDish(@RequestParam List<Long> ids){
        dishService.deleteWithFlavor(ids);

        // 清空redis缓存
        Set<Object> keys = redisTemplate.keys("dish_*");
        if (keys != null){
            redisTemplate.delete(keys);
        }

        return R.success("删除菜品成功！");
    }

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Dish::getStatus, status)
                .in(Dish::getId, ids);
        dishService.update(updateWrapper);
        return R.success("更新状态成功！");
    }

    @GetMapping("/list")
    public R<List<DishDto>> getDishList(Dish dish){
        List<DishDto> dishDtoList = null;

        // 以分类编号为key查找redis缓存
        String key = "dish_" + dish.getCategoryId();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            // 如果存在，则无需执行数据库查找
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime)
                .eq(Dish::getStatus, 1);
        List<Dish> list = dishService.list(queryWrapper);

        // 封装成DishDto
        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            // 加入分类名
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            // 加入口味
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(dishFlavors);

            return dishDto;
        }).collect(Collectors.toList());

        // redis缓存不存在则加入缓存中
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }
}
